package com.ustarlink.live.fragment;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.ustarlink.live.category.Category;
import com.ustarlink.live.category.CategoryAdapter;
import com.ustarlink.live.channel.Channel;
import com.ustarlink.live.channel.ChannelOpenHelper;
import com.ustarlink.live.channel.ChannelsAdapter;
import com.ustarlink.live.R;

import java.util.ArrayList;


public class EPGFragment extends Fragment {

    public static final String TAG = "EPGFragment";
    Context context;
    ListView cat_container, cha_container;
    private ChannelsAdapter channelsAdapter;
    private CategoryAdapter categoryAdapter;
    TextView textView_category;
    Bundle args;
    ChannelOpenHelper channelOpenHelper;
    OnChannelListItemSelectedListener listener;
    private View view;


    public EPGFragment() {
    }

    @Override
    public void onAttach(Context context) {

        super.onAttach(context);
        channelOpenHelper = new ChannelOpenHelper(context);
        try {
            listener = (OnChannelListItemSelectedListener) getActivity();
        } catch (ClassCastException e){
            throw new ClassCastException(context.toString() + "must implement OnChannelListItemSelectedListener");
        }


    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null == view) {
            view = inflater.inflate(R.layout.fragment_epg, container, false);
        }

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (view.isFocusable()){
            Log.i("is Focusable",TAG);
        } else {
            view.requestFocus();
            Log.i("requestFocus",TAG);
        }
        context = view.getContext();
        cat_container = (ListView)view.findViewById(R.id.lv_first_menu);
        cha_container = (ListView)view.findViewById(R.id.lv_second_menu);
        textView_category = (TextView)view.findViewById(R.id.tv_category_guide);
        channelOpenHelper = new ChannelOpenHelper(getActivity());
        SQLiteDatabase db = channelOpenHelper.getReadableDatabase();

        new SQLForLive(db).invoke();

    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private class SQLForLive {
        private SQLiteDatabase db;

        public SQLForLive(SQLiteDatabase db) {
            this.db = db;
        }

        public void invoke() {
            String queryChannels = "select  _id AS _id, " +
                    "id, " +
                    "channelName, " +
                    "channelUrl," +
                    " category from channels";
            //   String QueryCategory = "select category from channels group by category having count(category) > 1";
            final Cursor cChannel = db.rawQuery(queryChannels, null);

            fillChannelList(cChannel);

            String queryCategory = "select _id AS _id, " +
                    "category from channels " +
                    "group by " +
                    "category " +
                    "having count(category) > 1";
            Cursor cCategory = db.rawQuery(queryCategory, null);


            fillCategoryList(cCategory);

            cat_container.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String categoryName = categoryAdapter.getItem(position).getCategoryName();
                    textView_category.setText(categoryName);
                    categoryName = "\"" + categoryName + "\"";
                    String sqlChannelByCategory = "select  _id AS _id," +
                            " id, " +
                            "channelName, " +
                            "channelUrl, " +
                            "category " +
                            "from channels  where category=" + categoryName;
                    Cursor tmpChannel = db.rawQuery(sqlChannelByCategory, null);
                    fillChannelList(tmpChannel);
                }
            });

            cha_container.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                    String url = channelsAdapter.getItem(position).getChannelUrl();
                    Log.i(TAG, url);
//                    listener.onChannelListItemSelected(url);
                    FragmentManager fm = getFragmentManager();
                    fm.popBackStack();
                    fm.beginTransaction()
                            .replace(R.id.container, new VideoViewFragment(),VideoViewFragment.TAG)
                            .remove(EPGFragment.this)
                            .commit();
                }
            });

        }

        private void fillCategoryList(Cursor cCategory) {
            ArrayList<Category> categories;
            categories = new ArrayList<Category>();
            Category curCategory = null;
            while (cCategory.moveToNext()){
                curCategory = new Category();
                curCategory.setCategoryId(cCategory.getString(0));
                curCategory.setCategoryName(cCategory.getString(1));
              //  Log.i(TAG, curCategory.toString());
                categories.add(curCategory);
            }

            categoryAdapter = new CategoryAdapter(context, -1, categories);
            cat_container.setAdapter(categoryAdapter);
        }

        private void fillChannelList(Cursor cChannel) {
            ArrayList<Channel> channels;
            channels = new ArrayList<Channel>();
            Channel curChannel = null;
            while (cChannel.moveToNext()){
                curChannel = new Channel();
                curChannel.setId(cChannel.getString(1));
                curChannel.setChannelName(cChannel.getString(2));
                curChannel.setChannelUrl(cChannel.getString(3));
                curChannel.setCategoryName(cChannel.getString(4));

            //    Log.i(TAG, curChannel.toString());
                channels.add(curChannel);
            }
            channelsAdapter = new ChannelsAdapter(context, -1, channels);
            cha_container.setAdapter(channelsAdapter);
        }
    }

    public interface OnChannelListItemSelectedListener {

        public void onChannelListItemSelected(String url);
    }


}
